package com.sunck.common.shiro;

import com.sunck.common.utils.RedisUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import java.util.Collection;
import java.util.Set;

/**
 * redis自定义授权缓存管理类
 *
 * @author LengChen
 * @version 1.0
 * @date 2020/8/7
 */
public class RedisCache<K, V> implements Cache<K,V> {


    public RedisUtils redisUtils;

    private String cacheKeyName = null;

    public RedisCache(String cacheKeyName,RedisUtils redisUtils) {
        this.cacheKeyName = cacheKeyName;
        this.redisUtils = redisUtils;
//			if (!redisUtils.exists(cacheKeyName)){
//				Map<String, Object> map = Maps.newHashMap();
//				redisUtils.setObjectMap(cacheKeyName, map, 60 * 60 * 24);
//			}
//			logger.debug("Init: cacheKeyName {} ", cacheKeyName);
    }


    @Override
    public V get(K key) throws CacheException {
        if(key == null){
            return null;
        }
        return (V)redisUtils.getHashValue(cacheKeyName,key.toString());
    }

    @Override
    public V put(K key, V value) throws CacheException {
        if (key == null){
            return null;
        }
        redisUtils.setHash(cacheKeyName,key.toString(),value);
        return value;
    }

    @Override
    public V remove(K key) throws CacheException {
        V value = null;
        value =  (V)redisUtils.getHashValue(cacheKeyName,key.toString());
        redisUtils.removeHashKey(cacheKeyName,key.toString());
        return value;
    }

    @Override
    public void clear() throws CacheException {
        redisUtils.removeKey(cacheKeyName);
    }


    @Override
    public int size() {
        return redisUtils.getHashSize(cacheKeyName);
    }

    /**
     * 获取缓存中所有的keys值
     */
    @Override
    public Set<K> keys() {
        return redisUtils.getHashKeys(cacheKeyName);
    }

    /**
     * 获取缓存中所有的values值
     */
    @Override
    public Collection<V> values() {
        return redisUtils.getHashValues(cacheKeyName);
    }
}
